#include<iostream>
#include<stdarg.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<strings.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<functional>
#include<unordered_map>
#include"Log.hpp"

using func_t = std::function<std::string(const std::string& str,uint16_t ,const std::string&)>;


Log log;

enum{
    SOCKET_ERR=1 ,
    BIND_ERR=2
};
uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport,const std::string& ip = defaultip)
        :port_(port),
         ip_(ip) , 
         sockfd_(0),
         isrunning_(false)
    {}
    void Init()
    {
       
        //1.创建udp socket,udp的套接字是全双工的,允许同时读写
        sockfd_ = socket(AF_INET,SOCK_DGRAM,0);
        if(sockfd_ < 0)
        {
            log(Fatal,"socket create error,socketfd: %d",sockfd_);
            exit(SOCKET_ERR);
        }
        log(Info,"socket create success,socketfd: %d",sockfd_);

        //2.bind socket
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);  //需要保证端口号是网络字节序列,因为端口号是要发送给对方的
                                        //htons()从主机序列转网络序列
        local.sin_addr.s_addr = inet_addr(ip_.c_str());      //1.string->uint32_t  //uint32_t必须是网络序列的
        //local.sin_addr.s_addr = INADDR_ANY;
       
        if(bind(sockfd_,(const struct sockaddr*)&local,sizeof(local)) < 0)
        {
            log(Fatal,"bind error,errno: %d,err string: %s",errno,strerror(errno));
            exit(BIND_ERR);
        }
        log(Info,"bind sucess,errno: %d,err string: %s",errno,strerror(errno));
    }
    
    void CheckUser(const struct sockaddr_in& client,const std::string& clientip,uint16_t& clientport)
    {

        auto iter = online_user.find(clientip);
        if(iter == online_user.end())
        {
            online_user.insert({clientip,client});
            std::cout<<"["<<clientip<<":"<<clientport<<"] add to online user ."<<std::endl;
        }
    }

    void Broadcast(const std::string& info,const std::string& clientip,uint16_t clientport)
    {
        for(const auto& user:online_user )
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]#";
            message += info;
            socklen_t len = sizeof(message);
            sendto(sockfd_,message.c_str(),message.size(),0,(const sockaddr*)(&user.second),len);
        }
    }

    void Run() //func_t func)
    {
        isrunning_ = true;
        char inbuffer[size];
        while(isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_,inbuffer,sizeof(inbuffer) - 1,0,(struct sockaddr*)&client,&len);
            if(n < 0)
            {
                log(Warning,"recvfrom error,errno: %d,err string: %s",errno,strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);

            
            CheckUser(client,clientip,clientport);

            std::string info = inbuffer;
            Broadcast(info,clientip,clientport);//广播

            // inbuffer[n] = 0;
            
            // std::string echo_string = info;
            //std::string echo_string = func(info,clientport,clientip);

           
            // std::cout<<echo_string<<std::endl;
            
            // sendto(sockfd_,echo_string.c_str(),echo_string.size(),0,(const sockaddr*)&client,len);
        }
    }

    ~UdpServer()
    {
        if(sockfd_ > 0)
        {
            close(sockfd_);
        }
    }

private:
    int sockfd_;     //网络文件描述符
    uint16_t port_;   //端口号
    std::string ip_;  //ip地址,任意地址绑定0
    bool isrunning_;
    std::unordered_map<std::string,struct sockaddr_in> online_user;   //键值对<clinetip,client>
};


